package com.halflife.shiro.filter;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;

/**
 * Created by zhaoyf on 2018/2/25.
 */
public class AuthenticationFilter extends FormAuthenticationFilter {
    enum LoginType{
        ADMIN,RIDER,MERCHANT
    }
    private String prefix_admin;
    private String prefix_rider;
    private String prefix_merchant;
    private Integer login_type;
    public AuthenticationFilter(Map<String, String> param) {
        this.prefix_rider = param.get("prefix_rider");
        this.prefix_admin = param.get("prefix_admin");
        this.prefix_merchant = param.get("prefix_merchant");
    }
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws UnknownAccountException, Exception {
        AuthenticationToken token = createToken(request, response);
        String password = request.getParameter("password");
        if (token == null) {
            String msg = "create AuthenticationToken error";
            throw new IllegalStateException(msg);
        }
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        String username = (String) token.getPrincipal();
        boolean adminLogin = false;
        return true;
    }
    public boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        Subject subject = SecurityUtils.getSubject();
        if(subject.isAuthenticated()){
            return true;
        }
        String contextPath = ((ShiroHttpServletRequest) request).getContextPath();
        ((HttpServletResponse) response).sendRedirect(contextPath+"/admin/login");
//        res.setStatus(403);
//        PrintWriter out = res.getWriter();
//        out.write("403");
//        out.close();
        return false;
    }
}
